Skip to content

[rshapes] Fix half-pixel offsets in DrawRectangleLines() - #6430

Merged
raysan5 merged 2 commits into
raysan5:masterfrom
Ne0nWinds:line-fix
Nov 23, 2026
Merged

raysan5 merged 2 commits into
raysan5:masterfrom
Ne0nWinds:line-fix

Conversation

@Ne0nWinds

@Ne0nWinds Ne0nWinds commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

DrawRectangleLines used the diagonal entries of the transform matrix to compute half-pixel offsets.

There were two main problems with this approach:

  1. Using the diagonal entries is only correct for a non-rotated matrix. In fact, there's a pathological case at 90 degrees where the diagonal entries are zero (or nearly zero at angles close to 90 degrees)
  2. It completely ignored the scale and rotation of a camera when rendering with BeginMode2D.

Repro: Push/Pop Matrices

Using rlRotatef to rotate the rectangle by 90 degrees causes the rectangle to become invisible. All rotation matrices cause the offsets to be incorrect, but this is the most obvious example.

rlPushMatrix();
    rlTranslatef(screenWidth/2, screenHeight/2, 0.0);
    rlRotatef(90, 0, 0, 1);
    DrawRectangleLines(-50, -50, 100, 100, GREEN);
rlPopMatrix();

Repro: BeginMode2D with a camera

The half-pixel offsets completely ignore the modelview matrix. This is most obvious when rendering with BeginMode2D(camera). Simple example:

const int screenWidth = 800;
const int screenHeight = 450;

Camera2D camera = { 0 };
camera.offset = (Vector2){ screenWidth/2, screenHeight/2 };
camera.zoom = 100.0f; // This bug is more obvious with a very large zoom
BeginMode2D(camera);
    DrawRectangle(-1, -1, 2, 2, DARKGRAY);
    DrawRectangleLines(-1, -1, 2, 2, RED);
EndMode2D();

In the example above, the DrawRectangle draws a significantly larger rectangle than DrawRectangleLines!

Solution

  1. Multiply the transform matrix (rlGetMatrixTransform) with the modelview matrix (rlGetMatrixModelview). We only need the upper-left 2x2 section of the matrix for 2D lines.
  2. Take the inverse of step 1: this tells us how many world space units correspond to one pixel.
  3. Use inverse matrix to map screen-space pixel-diamond half-axes (0.5, 0) and (0, 0.5) to world space via 2x2 inverse (more info in PR thread)

@Ne0nWinds Ne0nWinds changed the title [rshapes] Fix half-pixel offsets in DrawRectangleLines [rshapes] Fix half-pixel offsets in DrawRectangleLines() Nov 19, 2026
@raysan5

raysan5 commented Nov 21, 2026

Copy link
Copy Markdown
Owner

@Ne0nWinds I'm afraid I prefer to avoid that fix. It requires adding more compute cost to every draw line just to align one pixel in certain cases, it could be GPU-dependant (in the past I got different results on Intel/Nvidia and even RPI Broadcom GPUs for pixel alignment on lines) and it adds an extra function that should be called on all line-drawing functions (actually, I'm removing the EaseCubicInOut() after seeing this PR).

Despite that, I think it can be added as a commented block of code for users really facing this issue and to have a note on how it can be addressed if really crucial for their projects.

@Ne0nWinds

Ne0nWinds commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

@raysan5 I'm not sure if I was clear in the description. DrawRectangleLines and DrawRectangleRoundedLines already have half-pixel offset calculations in master. The problem is that they're incorrect.

Some examples with videos/screenshots:

1. Rotation

Rotating with rlRotatef() causes the rectangle to scale in a weird way. You can see the rectangle becomes invisible at 90 degrees due to the divide by zero.

rotation += 0.1f; // rotate the rectangle every single frame
rlPushMatrix();
  rlTranslatef(screenWidth/2, screenHeight/2, 0.0f);
  rlRotatef(rotation, 0, 0, 1);
  DrawRectangleLines(-50, -50, 100, 100, GREEN);
rlPopMatrix();
draw_rectangle_lines_rotate.mp4

2. DrawRectangle is inconsistent with DrawRectangleLines

DrawRectangleLines makes the rectangle too small when drawing with a camera zoom greater than 1.0

BeginMode2D(camera); // offset = { 400, 225 }, zoom = 100.0f
  DrawRectangle(-1, -1, 2, 2, DARKGRAY);
  DrawRectangleLines(-1, -1, 2, 2, RED);
EndMode2D();
draw_rectangle_lines_camera2d

3. DrawRectangleRoundedLines with camera

DrawRectangleRoundedLines misbehaves when camera zoom is set to greater than 1.0

// increment roundness by 0.005f every frame until it reaches 1.0f
BeginMode2D(camera); // offset = { 400, 225 }, zoom = 100.0f
  DrawRectangleRounded((Rectangle){ -1, -1, 2, 2 }, roundness, 16, DARKGRAY);
  DrawRectangleRoundedLines((Rectangle){ -1, -1, 2, 2 }, roundness, 16, RED);
EndMode2D();
draw_rectangle_rounded_lines_offsets.mp4

My PR fixes all 3 of these issues by correcting the math for the existing half-pixel offsets. We can't remove the half-pixel offsets; otherwise, we'd re-open issues like this:
#4756
#4386

We could optionally apply this half-pixel offsets to other DrawLine*() functions to make them consistent with the DrawRectangle*Lines() functions, but that's outside the scope of this PR (although there was an issue about this in the past that was never properly fixed: #3931)

@raysan5

raysan5 commented Nov 22, 2026

Copy link
Copy Markdown
Owner

@Ne0nWinds I see, thanks for the further explanation and the videos. I use those functions a lot in many of my tools and I worried that change could break something (never had problems on my specific use cases).

Still, I'd would prefer to avoid a new costly function to address that specific use case. Could it be addressed in a simpler way using less operations or at least avoiding the sqrtf()?

@Ne0nWinds

Copy link
Copy Markdown
Contributor Author

I looked into this a bit more. I found a solution that's a bit faster and is more mathematically correct. I removed the call to sqrtf AND I was able to get rid of one floating-point division (master uses two!)

My new proposed solution would be something like this:

// Compute upper-left 2x2 of M*T
float ax = m.m0*t.m0 + m.m4*t.m1;
float ay = m.m1*t.m0 + m.m5*t.m1;
float bx = m.m0*t.m4 + m.m4*t.m5;
float by = m.m1*t.m4 + m.m5*t.m5;

// Map screen-space pixel-diamond half-axes (0.5, 0) and (0, 0.5) to world space via 2x2 inverse
float invDet = 0.5f/fabsf(ax*by - ay*bx);
float xOffset = fmaxf(fabsf(bx), fabsf(by))*invDet;
float yOffset = fmaxf(fabsf(ax), fabsf(ay))*invDet;

This does two things:

  1. Uses the 2x2 inverse of M*T. This allows us to directly compute how much to move the vertices without using sqrtf and only one division
  2. Takes advantage of OpenGL's line rasterization rules. The fmaxf(fabsf(bx), fabsf(by)) replicates OpenGL's diamond-exit rule for lines

The OpenGL spec says that a line should be rasterized by testing if it exits an implicit diamond shape within a pixel, which is given by |x - cx| + |y - cy| <= 0.5, where x/y are a pixel screen coordinates and cx/cy are the nearest pixel center. This tells the minimum we have to move the line endpoint so that it rasterizes in the correct pixel

(0,0)----*----(1,0)
  |     / \     |
  |    /   \    |
  *---( .5  )---*
  |    \   /    |
  |     \ /     |
(0,1)----*----(1,1)

About the performance:

  • fabsf is usually implemented as a single bitwise AND instruction (just clears the sign bit)
  • fmaxf is surprisingly slow because it has to handle certain edge cases (like NaN). For the final version, I'd replace that with a simple ternary (example: (a > b)? a : b). It's slightly less readable, but it guarantees the compiler will produce optimal output (like a single maxss instruction on x64)
  • I think the 2x2 matrix multiplication is unavoidable if this function should work correctly under any transform

@raysan5 Would this approach work for you? If so, I'll update the PR with it

@raysan5

raysan5 commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Would this approach work for you? If so, I'll update the PR with it

@Ne0nWinds thanks for the further review and improvement, new proposed solution looks way better to me but please, could we avoid the additional function and just add that code to DrawRectangleLines() and DrawRectangleRoundedLines() for now?

@raysan5
raysan5 merged commit 4880766 into raysan5:master Nov 23, 2026
15 checks passed
@raysan5

raysan5 commented Nov 23, 2026

Copy link
Copy Markdown
Owner

@Ne0nWinds thank you veery much for the improvement and the review!

@Ne0nWinds

Copy link
Copy Markdown
Contributor Author

Wow, you merged that super fast! I was going to post some additional info:

I made sure the ternary optimizes down to a few cheap CPU instructions: https://godbolt.org/z/GTTKdM4bE

Also, DrawRectangleLines and DrawRectangle are now in near pixel-perfect agreement with every matrix transformation I tried: rotation, scaling, shearing, etc

pr_rotate_demo.mp4

Also, there have been many reported issues for drawing lines in the past, some of which never quite got resolved. Examples:

  1. [rshapes] Off-by-one difference between DrawRectangleLinesEx and DrawLine/DrawLineV at drawing position. #3931
  2. [rshapes] Horizontal and Vertical Lines Starting at {0, 0} Not Drawing in Raylib #4130

Applying a similar fix to the DrawLine*() functions has the potential to finally resolve those issues. master actually hits some driver-dependent behavior in those functions (as you mentioned earlier). The line endpoints land between two different pixels, forcing the driver to pick one or the other.

It's up to you if the extra math in the DrawLine*() functions is worth it. It would have to be tested on various low-end GL drivers (which don't always follow the GL spec strictly). However, I do think it's worth investigating, at the very least.

@Ne0nWinds
Ne0nWinds deleted the line-fix branch November 23, 2026 19:46
@raysan5

raysan5 commented Nov 23, 2026

Copy link
Copy Markdown
Owner

@Ne0nWinds thanks for additional info, great to know it's so optimized.

yeah, there have been so many attempts to address that pixel offset that I'm quite skeptic but we can try one last time and see if it works (still, I think it could be driver/GPU-dependant). What are the DrawLine*() functions affected? Mayb it can be applied only the most common one(s).

@Ne0nWinds

Copy link
Copy Markdown
Contributor Author

I think these four functions would be affected:

  1. DrawLine
  2. DrawLineV
  3. DrawLineStrip
  4. DrawLineDashed

These two are not affected because they don't render with RL_LINES:

  1. DrawLineEx
  2. DrawLineBezier

The easiest one to start with would be DrawLine, which is also probably the most commonly used one.

I also think we actually may be able to simplify the math a bit further for these functions too. They don't have the same concerns that DrawRectangleLines() has 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants